package com.xiaocai.myblog.controller;

import com.google.common.base.Preconditions;
import com.xiaocai.myblog.common.ResponseData;
import com.xiaocai.myblog.common.SuccessResponseData;
import com.xiaocai.myblog.domain.User;
import com.xiaocai.myblog.enums.ErrorCodeEnum;
import com.xiaocai.myblog.exception.BusinessException;
import com.xiaocai.myblog.services.UserService;
import com.xiaocai.myblog.utils.MD5Util;
import com.xiaocai.myblog.utils.RedisUtil;
import com.xiaocai.myblog.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author chenhefu
 * @date 2019-09-27 20:45
 */
@RestController
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;

    @RequestMapping(value = "api/v1/login",method = RequestMethod.POST)
    public ResponseData<User> login(@RequestParam String email,@RequestParam String password
            ,@RequestParam String verifyCode){
        Preconditions.checkArgument(StringUtils.isNotEmpty(email), "邮箱或者密码不能为空");
        Preconditions.checkArgument(StringUtils.isNotEmpty(verifyCode), "验证码不能为空");

        String pwd = MD5Util.generate(password);

        checkCode(email,verifyCode);

        User user = userService.login(email, pwd);

        return SuccessResponseData.getSuccessData(user);
    }

    @RequestMapping(value = "api/v1/register", method = RequestMethod.POST)
    public ResponseData<Boolean> register(@RequestBody UserVO user){
        Preconditions.checkArgument(StringUtils.isNotEmpty(user.getEmail()),"邮箱或者密码不能为空");
        Preconditions.checkArgument(StringUtils.isNotEmpty(user.getPassword()),"邮箱或者密码不能为空");

        boolean isSuccess = userService.register(createUser(user));

        return SuccessResponseData.getSuccessData(isSuccess);
    }

    private User createUser(UserVO userVO){
        User user = new User();
        user.setEmail(userVO.getEmail());
        user.setPassword(MD5Util.generate(userVO.getPassword()));
        return user;
    }

    private void checkCode(String email, String verifyCode){
        String key = "send_email_key_" + email;
        String code = (String) redisUtil.get(key);
        if (StringUtils.isEmpty(code)){
            throw new BusinessException(ErrorCodeEnum.SERVER_ERROR_PARAM, "发送验证码中");
        }
        if (!code.equals(verifyCode)){
            throw new BusinessException(ErrorCodeEnum.SERVER_ERROR_PARAM, "验证码错误");
        }

        long expire = redisUtil.getExpire(key);
        if (expire <= 0){
            throw new BusinessException(ErrorCodeEnum.BUSINESS_ERROR, "验证码已经过期,请重新发送");
        }
    }
}
